package com.java1412.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author java1412
 * @since 2023-06-07 11:19:57
 */
@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取当前请求的上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取请求对象
        HttpServletRequest request = ctx.getRequest();
        System.out.println(request.getMethod() + "," + request.getRequestURL().toString());
        // 从request中可以获取token
        String token = request.getParameter("token");
        // 对令牌做判断
        if (token == null) {
            // 没有令牌
            System.out.println("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                // 响应给浏览器结果
                ctx.getResponse().getWriter().write("token is empty");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        return ctx;
    }
}
